package pl.edu.agh.iosr.gamblingzone.dao.ejb;

import java.util.List;

import pl.edu.agh.iosr.gamblingzone.dao.UserDAO;
import pl.edu.agh.iosr.gamblingzone.model.User;

/**
 * The Class UserDAOBean.
 */
public class UserDAOBean extends GenericDAOBean<User, Long> implements UserDAO {

	/* (non-Javadoc)
	 * @see pl.edu.agh.iosr.gamblingzone.dao.UserDAO#findByLogin(java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	public User findByLogin(String login) {

		if (login == null || login.length() <= 0) {
			return null;
		}

		List<User> userList = getEntityManager()
			.createQuery("select u from USERS u" +
				" where u.loginName like :login")
			.setParameter("login", login)
			.getResultList();

		if (userList == null || userList.size() <= 0) {
			return null;
		}

		return userList.get(0);
	}

	/* (non-Javadoc)
	 * @see pl.edu.agh.iosr.gamblingzone.dao.UserDAO#authenticateUser(java.lang.String, java.lang.String)
	 */
	public boolean authenticateUser(String login, String password) {
		
		User user = findByLogin(login);
		if(user == null) {
			return false;
		}
		if(user.getPassword() == null || !user.getPassword().equals(User.computeSHA1(password))) {
			return false;
		}
		
		return true;
	}
}
